package cn.maihe.elg.operation.supports.sms;

import cn.maihe.elg.operation.config.TencentSmsConfig;
import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.SmsResultBase;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.httpclient.PoolingHTTPClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @Description
 * @Author caixh
 * @Date 2021/10/8.
 */
@Service
@Slf4j
public class TencentCloudSmsService {
    private TencentSmsConfig tencentSmsConfig;
    private SmsSingleSender ssender;

    public TencentCloudSmsService(TencentSmsConfig tencentSmsConfig){
        Assert.notNull(tencentSmsConfig.getAppid(), "tencent.sms.appid");
        Assert.hasText(tencentSmsConfig.getAppkey(), "tencent.sms.appkey");
        Assert.notNull(tencentSmsConfig.getCodeTemplateId(), "tencent.sms.codeTemplateId");
        Assert.hasText(tencentSmsConfig.getSignName(), "tencent.sms.signName未配置");
        this.tencentSmsConfig = tencentSmsConfig;

        // 创建一个连接池 httpclient, 并设置最大连接量为10
        PoolingHTTPClient httpclient = new PoolingHTTPClient(10);
        this.ssender = new SmsSingleSender(tencentSmsConfig.getAppid(), tencentSmsConfig.getAppkey(),httpclient);

    }

    /**
     * 短信模板内容：{}为您的登录验证码，请于{}分钟内填写，如非本人操作，请忽略本短信。
     */
    public void sendAuthCodeSms(String targetMobile,String code,String minute){
        String[] params = {code,minute};
        sendSms(targetMobile,tencentSmsConfig.getCodeTemplateId(),params);
    }
    /**
     * 【中天担保】
     *   {1}已过解密时间{2}，烦请贵单位还没完成解密工作抓紧安排，避免因未解密没收保证金。(如已完成解密工作，请忽略此提醒短信)
     *   其中{1}代表项目名称，{2}指已过投保截止时间分钟数
     */
    public void sendDecryptNoticeMsg(String targetMobile,String projectName,String minute){
        if("1".equals(tencentSmsConfig.getDecryptNoticeSendFlag())) {
            String[] params = {projectName, minute};
            sendSms(targetMobile, tencentSmsConfig.getDecryptNoticeTemplateId(), params);
            log.info("[已发送]发送解密提醒短信={}--{}--{}",targetMobile,projectName,minute);
        }else{
            log.info("[已关闭]发送解密提醒短信={}--{}--{}",targetMobile,projectName,minute);
        }
    }
    /**
     * 若异常则 保存发送内容，间隔多久重新发送，重试几次均失败则丢弃，其他则标识发送成功
     *
     * @param targetMobile
     * @param templateCode
     * @param params
     */
    private void sendSms(String targetMobile, int templateCode, String[] params) {
        try {
            SmsResultBase result = ssender.sendWithParam("86", targetMobile, templateCode, params, tencentSmsConfig.getSignName(), "", "");
            String responseBody = result.getResponse().body;
            if(StringUtils.isNotEmpty(responseBody)){
                JSONObject resJo = JSONObject.parseObject(responseBody);
                if(0==resJo.getInteger("result")){
                    return;
                }else{
                    log.error("短信发送失败:{}",resJo.getString("errmsg"));
                }
            }
            throw new RuntimeException("短信发送失败:响应报文为空");
        } catch (Exception e) {
            throw new RuntimeException("短信发送异常:" + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {

        TencentSmsConfig config = new TencentSmsConfig();
        config.setAppid(1400576908);
        config.setAppkey("599a0db6598b168b0c5fac69777a34ee");
        config.setSignName("中天担保");
        config.setCodeTemplateId(1139794);
        config.setDecryptNoticeTemplateId(1731991);
        config.setDecryptNoticeSendFlag("1");

        TencentCloudSmsService s = new TencentCloudSmsService(config);
        for(int i=0;i<2;i++){
            s.sendDecryptNoticeMsg("13959192729", "项目名称-南平市光泽县X120--X123东廷线闽清北站至东桥朱山段公路工程（A段:K0+000~k7+960）", "15分钟");
        }
    }
}
